package com.itheima.day27;

import com.itheima.dao.UserMapper;
import com.itheima.bean.User;
import com.itheima.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //设置网页的编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        //注册的页面 首先获得用户输入的用户名和密码
        String userName = req.getParameter("username");
        String passWord = req.getParameter("password");
        //使用mybatis判断用户名是否重复  使用自动提交事务的会话
        SqlSession autoCommitSession = MybatisUtil.getAutoCommitSession();
        UserMapper mapper = autoCommitSession.getMapper(UserMapper.class);
        User user = mapper.selectByUserName(userName);
        //设置网页为utf-8
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        if(user == null){
            //用户名不存在可以注册
            user = new User();
            user.setName(userName);
            user.setPassWord(passWord);
            //使用mybatis将用户对象写入数据库
            mapper.addUser(user);
            //弹窗提示用户注册成功  并且跳转到登录界面
            writer.println("<script>");
            writer.println("alert('注册成功')");
            //跳转到登录的页面
            writer.print("location.href='login.html';");
            writer.println("</script>");
            System.out.println("用户:" + userName + "注册成功");
        }else{
            //用户名存在注册失败
            writer.println("<script>");
            writer.println("alert('用户名已存在,注册失败')");
            //跳转到登录成功的页面
            writer.print("location.href='login.html';");
            writer.println("</script>");
        }
        //关闭会话
        autoCommitSession.close();
    }
}













